package com.app.conf.source;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @ClassName:DataSourceTwoMapperConfig
 * @Description TODO
 * @Author zk_yjl
 * @Date 2021/9/2 12:29
 * @Version 1.0
 * @Since 1.0
 **/
@Configuration
@MapperScan(
        basePackages="com.app.mapper.subei", //配置扫描的mapper接口
        sqlSessionFactoryRef = "sqlSessionFactorySubei", //使用的Factory
        sqlSessionTemplateRef = "sqlSessionTemplateSubei") //使用的SqlSessionTemplate
public class DataSourceSubeiConfig {
    @Resource(name="dataSourceSubei")
    private DataSource dataSourceSubei;
    /**本数据源扫描的mapper路径*/
    static final String MAPPER_LOCATION = "classpath:mapper/subei/**/*.xml";
    /**
     * 创建SqlSessionFactory 对象
     */
    @Bean(name="sqlSessionFactorySubei")
    public SqlSessionFactory sqlSessionFactorySubei(){
        try{
            MybatisSqlSessionFactoryBean sqlSessionFactoryBean=new MybatisSqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(dataSourceSubei);
            //设置mapper配置文件
            sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
            MybatisConfiguration configuration = new MybatisConfiguration();
            configuration.setMapUnderscoreToCamelCase(true);
            sqlSessionFactoryBean.setConfiguration(configuration);
            return sqlSessionFactoryBean.getObject();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 配置事务
     * @param dataSourceSubei
     * @return
     */
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManagerSubei(
            @Qualifier("dataSourceSubei") DataSource dataSourceSubei) {
        return new DataSourceTransactionManager(dataSourceSubei);
    }
    /**
     * 通过SqlSessionFactory 创建 SqlSessionTemplate
     * @return
     */
    @Bean(name="sqlSessionTemplateSubei")
    public SqlSessionTemplate sqlSessionTemplate(){

        return new SqlSessionTemplate(sqlSessionFactorySubei());
    }
}

